package com.tenc.config.listener;

import com.tenc.feign.InitService;
import com.tenc.pojo.ErrorJson;
import com.tenc.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * @author Alan
 * @description key过期监听
 * @ClassName RedisKeyExpirationListener
 * @since 2021/7/27
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Value("${wechat.company.corpid}")
    private String corpid;
    @Value("${wechat.company.corpsecret}")
    private String corpsecret;

    @Autowired
    InitService initService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 处理微信Token过期
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        if(message.toString().equals("acToken")){
            ErrorJson json = initService.getAccessToken(corpid,corpsecret);
            if(json.getErrcode()!=0){
                log.info("access_token获取失败\n错误原因：{}",json);
                //TODO 写入数据库日志
            }else{
                log.info("获取到AccessToken：{}",json);
                RedisUtil.set("acToken",json.getAccess_token());
                RedisUtil.expire("acToken",7200);
                //TODO 写入数据库日志
            }
        }
    }
}
